package com.ming.sps.server.action;

import com.ming.sps.server.bean.ParamMap;
import com.ming.sps.server.utils.AddressResolutionUtil;
import com.ming.sps.server.utils.DateTimeUtil;
import com.ming.sps.server.utils.MingUtil;
import com.ming.sps.server.utils.QueueNumberCreator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class LimitBaseAction extends BaseAction {

    @RequestMapping("applyNewLicense")
    @ResponseBody
    public String applyNewLicense() throws Exception {
        Map<String,Object> map  = requestParam(getRequest());
        String ret = "";
        String queueno = (map.get("queueno") != null && !"".equals(map.get("queueno"))) ? map.get("queueno").toString() : null;
        if(queueno != null) {
            ParamMap queueMap = dao.queryOneBySql("select * from t_limitqueue where ISHANDLE='0' and SEQNO='" + queueno + "'");
            int currentposition = queueMap.getInteger("CURRENTPOSITION");
            ParamMap configMap = dao.queryOneBySql("select * from t_limitconfig where SEQNO='" + queueno.substring(0, queueno.length() - 5) + "'");
            if(configMap == null) {
                return "{\"status\" :\"200\", \"msg\": \"未配置合理规划布局，可以提交\"}";
            }
            int maxnum = configMap.getInteger("MAXNUM");
            int currentnum = configMap.getInteger("CURRENTNUM");
            if(maxnum > currentnum) {
                if(currentposition < (maxnum - currentnum)) {
                    ret = "{\"status\" :\"200\", \"msg\": \"名额未满，可以提交\"}";
                } else {
                    ret = "{\"status\": \"303\", \"msg\":\"您的排队号是：" + queueno + "，前面还有" + currentposition + "在排队，请耐心等待轮候，轮到您办理时，我们会以短信的方式提醒您过来办理，谢谢！\"}";
                }
            } else {
                ret = "{\"status\": \"304\", \"msg\":\"您的排队号是：" + queueno + "，前面还有" + currentposition + "在排队，请耐心等待轮候，轮到您办理时，我们会以短信的方式提醒您过来办理，谢谢！\"}";
            }
        } else {
            String configid = map.get("limitconfigid") == null ? null : map.get("limitconfigid").toString();
            if (configid == null) {
                String address = map.get("bizAddrStreet").toString();
                if(address.indexOf("省") == -1) {
                    address = "广东省" + address;
                }
                List<Map<String, String>> addrlist = AddressResolutionUtil.addressResolution(address);
                if (addrlist != null && addrlist.size() > 0) {
                    Map<String, String> addressMap = addrlist.get(0);
                    List<ParamMap> list = dao.queryListBySql("select * from t_limitconfig where orgid = (select ID from tborganization where NAME like '%" + addressMap.get("county") + "%')");
                    ParamMap paramMap = getLimitConfig(list, addressMap);
                    if(paramMap != null) {
                        ret = getResult(map, paramMap);
                    } else {
                        paramMap.put("currentnum", paramMap.getInteger("currentnum") + 1);
                        dao.update("t_limitconfig", "id", paramMap);
                        ret = "{\"status\" :\"200\", \"msg\": \"未配置合理规划布局，可以提交\"}";
                    }
                }
            } else {
                ParamMap paramMap = dao.queryOneBySql("select * from t_limitconfig where id='" + configid + "'");
                if(paramMap == null) {
                    return "{\"status\" :\"200\", \"msg\": \"未配置合理规划布局，可以提交\"}";
                }
                ret = getResult(map, paramMap);
            }
        }
        return MingUtil.encrypt(ret);
    }

    private String getResult(Map<String, Object> map, ParamMap paramMap) throws Exception {
        String ret = "";
        int maxnum = paramMap.getInteger("maxnum");
        int currentnum = paramMap.getInteger("currentnum");
        String isqueue = paramMap.getString("isqueue");
        String seqno = paramMap.getString("seqno");
        String orgid = paramMap.getString("orgid");
        String id = paramMap.getString("id");
        ParamMap maxnumMap = dao.queryOneBySql("select max(CURRENTPOSITION) CURRENTPOSITION from t_limitqueue where ISHANDLE != '1' and SEQNO like '" + seqno + "%'");
        if (currentnum < maxnum) {
            if ("1".equals(isqueue)) {
                String queueno = createQueueNumber(seqno);
                int num = maxnumMap.getInteger("CURRENTPOSITION") + 1;
                ret = "{\"status\": \"301\", \"msg\":\"您的排队号是：" + queueno + "，前面还有" + num + "在排队，请耐心等待轮候，轮到您办理时，我们会以短信的方式提醒您过来办理，谢谢！\"}";
                insertQueue(map, id, orgid, queueno, num);
            } else {
                paramMap.put("currentnum", currentnum + 1);
                dao.update("t_limitconfig", "id", paramMap);
                ret = "{\"status\" :\"200\", \"msg\": \"名额未满，可以提交\"}";
            }
        } else {
            paramMap.put("isqueue", "1");
            dao.update("t_limitconfig", "id", paramMap);
            String queueno = createQueueNumber(seqno);
            int num = maxnumMap.getInteger("CURRENTPOSITION") + 1;
            ret = "{\"status\": \"302\", \"msg\":\"您的排队号是：" + queueno + "，前面还有" + num + "在排队，请耐心等待轮候，轮到您办理时，我们会以短信的方式提醒您过来办理，谢谢！\"}";
            insertQueue(map, id, orgid, queueno, num);
        }
        return ret;
    }

    private void insertQueue(Map<String, Object> params, String areaid, String orgid, String queueno, int currentposition) {
        Map<String, Object> map = new HashMap<>();
        map.put("ID", UUID.randomUUID().toString());
        map.put("NAME", params.get("picName"));
        map.put("MOBILE", params.get("lineTel"));
        map.put("CARDNO", params.get("picCidNo"));
        map.put("", params.get("bizAddrStreet"));
        map.put("CREATETIME", DateTimeUtil.getDateTime());
        map.put("AREAID", areaid);
        map.put("SEQNO", queueno);
        map.put("ISHANDLE", "0");
        map.put("ORGID", orgid);
        map.put("PLATFORM", "terminal");
        map.put("CURRENTPOSITION", currentposition);
        dao.insert("t_limitqueue", map);
    }

    private synchronized String createQueueNumber(String seqno) throws Exception {
        return QueueNumberCreator.getInstance().createQueueNumber(dao, seqno);
    }

    private ParamMap getLimitConfig(List<ParamMap> list, Map<String, String> addressMap) {
        ParamMap paramMap = null;
        if(list != null && list.size() > 0) {
            for(ParamMap map : list) {
                if(isHasParamMap(map, addressMap)) {
                    paramMap = map;
                    break;
                }
            }
        }
        return paramMap;
    }

    private boolean isHasParamMap(ParamMap map, Map<String, String> addressMap) {
        String managerArea = map.getString("managearea");
        String areaname = map.getString("name");
        String village = addressMap.get("village");
        String street = addressMap.get("street");
        if(village.equals(areaname)) {
            return true;
        }
        boolean result = false;
        if(managerArea != null && !"".equals(managerArea)) {
            String [] areas = managerArea.split("、");
            for(String area : areas) {
                if(area.indexOf(village) != -1 || street.indexOf(area) != -1 || area.indexOf(street) != -1) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }

    @RequestMapping("judgeInputQueueNo")
    @ResponseBody
    public String judgeInputQueueNo() throws Exception {
        Map<String,Object> map  = requestParam(getRequest());
        String address = map.get("bizAddrStreet").toString();
        if(address.indexOf("省") == -1) {
            address = "广东省" + address;
        }
        String ret = "";
        List<Map<String, String>> addrlist = AddressResolutionUtil.addressResolution(address);
        if (addrlist != null && addrlist.size() > 0) {
            Map<String, String> addressMap = addrlist.get(0);
            List<ParamMap> list = dao.queryListBySql("select * from t_limitconfig where orgid = (select ID from tborganization where NAME like '%" + addressMap.get("county") + "%')");
            ParamMap paramMap = getLimitConfig(list, addressMap);
            if("1".equals(paramMap.get("isqueue"))) {
                ret = "{\"input\": true}";
            } else {
                ret = "{\"input\": false}";
            }
        }
        return ret;
    }

    @RequestMapping("handleNewLicense")
    @ResponseBody
    public String handleNewLicense() {
        Map<String,Object> map  = requestParam(getRequest());
        String queueno = map.get("queueno").toString();
        String mincode = queueno.substring(0, queueno.length() - 5);
        try {
            dao.updateData("update t_limitqueue set CURRENTPOSITION=CURRENTPOSITION-1 where ISHANDLE = 0 and SEQNO like '" + mincode + "%'");
            dao.updateData("update t_limitqueue set ISHANDLE=1 where SEQNO='" + queueno + "'");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return MingUtil.encrypt("");
    }

}
